package cool.mtc.minghe.web.config;

import cool.mtc.minghe.service.service.websocket.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

/**
 * @author 明河
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketDisconnectListener implements ApplicationListener<SessionDisconnectEvent> {
    private final WebSocketService webSocketService;

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        log.info("SessionDisconnectEvent");
        WebSocketPrincipal user = (WebSocketPrincipal) event.getUser();
        if (null == user) {
            return;
        }

        webSocketService.offline(user.getSessionId());
    }
}
